<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true"
             v-show="showSearch" label-width="68px">



      <el-form-item label="动作名称" prop="actionName">
        <el-input
            style="width: 200px;"
          v-model="queryParams.actionName"
          placeholder="请输入动作名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="动作标识" prop="actionCode">
        <el-input
            style="width: 200px;"
          v-model="queryParams.actionCode"
          placeholder="请输入动作标识"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:action:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:action:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:action:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['system:action:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:action:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="actionList" @selection-change="handleSelectionChange" :header-cell-style="{backgroundColor: '#f8f8f9'}">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="关联的单据定义" align="center" prop="billDefine" :show-overflow-tooltip="true" />
      <el-table-column label="动作名称" align="center" prop="actionName" :show-overflow-tooltip="true" />
      <el-table-column label="动作标识" align="center" prop="actionCode" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="mini" link type="primary" icon="View" @click="handleView(scope.row)"
                     v-hasPermi="['system:action:query']">查看</el-button>
          <el-button size="mini" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:action:edit']">修改</el-button>
          <el-button size="mini" link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:action:remove']">删除</el-button>
          <el-button size="mini" link type="primary" icon="Delete" @click="handleLinkLinstner(scope.row)"
                     v-hasPermi="['system:BillDefine:remove']">添加监听</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 导入 对话框 -->
    <el-dialog :title="upload.title" v-model="upload.openup" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport"
                 :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                 :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled/></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                     @click="importTemplate">下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.openup = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改单据动作对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="actionRef" :model="form" :rules="rules" label-width="80px">
        <el-row>


  <el-col :span="12">
    <el-form-item label="动作名称" prop="actionName">
      <el-input v-model="form.actionName" placeholder="请输入动作名称" maxlength="32" show-word-limit />
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="动作标识" prop="actionCode">
      <el-input v-model="form.actionCode" placeholder="请输入动作标识" maxlength="32" show-word-limit />
    </el-form-item>
  </el-col>

        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>



<!--  详情按钮单据动作 -->
    <el-dialog :title="title" v-model="openview" width="800px" append-to-body>
      <el-form ref="actionViewRef" :model="formDetail" label-width="80px">
          <el-row>
                        <el-col :span="12">
                          <el-form-item label="关联的单据定义" prop="billDefine">
                            <span>{{formDetail.billDefine}}</span>
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item label="动作名称" prop="actionName">
                            <span>{{formDetail.actionName}}</span>
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item label="动作标识" prop="actionCode">
                            <span>{{formDetail.actionCode}}</span>
                          </el-form-item>
                        </el-col>

          </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openview=false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Action">
  import adminstyle from "@/store/modules/adminstyle";
import { listAction, getAction,
  delAction, addAction, updateAction }
  from "@/api/bill/action";

import {getToken} from "@/utils/auth.js";
    //常用引用
import { listAllCompany} from "@/api/digital/memorganizationinfo";//选择树状
import Treeselect from 'vue3-treeselect'
import 'vue3-treeselect/dist/vue3-treeselect.css'
import {parseTime, getSysId} from "@/utils/yingruan";

const { proxy } = getCurrentInstance();
const router = useRouter();

const actionList = ref([]);
const open = ref(false);
const openview = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

//常用自定义数据
//自定义
const dateRange= ref([parseTime(new Date(), "{y}-{m}-{d}"), parseTime(new Date(), "{y}-{m}-{d}")]);
const companyOptions= ref([]);
const defaultCompany= ref(null);//默认当前企业

const curSys = ref(null);//当前所属系统
const billDefineId = ref(null);

//导入参数
const upload = reactive({
  // 是否显示弹出层（用户导入）
  openup: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/stability/action/importData"
});

const data = reactive({
  form: {},
  formDetail:{},//详情
  queryParams: {
    keyword:null,
    pageNum: 1,
    pageSize: 10,
    billDefine: null,
    actionName: null,
    actionCode: null,
    actionLinsener: null
  },
  rules: {
  }
});

const { queryParams, form, rules, formDetail } = toRefs(data);

/** 查询单据动作列表 */
function getList() {
  loading.value = true;
  queryParams.value.billDefine = billDefineId.value;
  listAction(queryParams.value).then(response => {
    actionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
  function  handleLinkLinstner(row){
    proxy.$router.push({ path:"/tool/billlLinstner"   , query:{billDefineId:billDefineId.value,billActionId:row.id} });

  }
// 表单重置
function reset() {
  form.value = {
    id: null,
    billDefine: null,
    actionName: null,
    actionCode: null,
    actionLinsener: null
  };
  proxy.resetForm("actionRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");

  if(proxy.$refs.treeselectSearchCom)
  {
    proxy.$refs.treeselectSearchCom.clear();//清空树状选择
  }
  dateRange.value = [];

  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加单据动作";
  form.value.billDefine = billDefineId.value
  if(companyOptions.value.length>0){
    form.value.sysId = companyOptions.value[0].id;
  }
  else{
    if(proxy.$refs.treeselectCom)
    {
      proxy.$refs.treeselectCom.clear()
    }
  }
  changeDept();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getAction(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改单据动作";
    changeDept();
  });
}


/** 详情按钮操作 */
function handleView(row) {
  reset();
  const _id = row.id || ids.value
  getAction(_id).then(response => {
    formDetail.value = response.data;
    openview.value = true;
            title.value = "查看单据动作";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["actionRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateAction(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAction(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除单据动作选中的数据项？').then(function() {
    return delAction(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('stability/action/export', {
    ...queryParams.value
  }, `单据动作_${new Date().getTime()}.xlsx`)
}

/** 树形数据转换 */
function normalizer(node) {
  if (node.children && !node.children.length) {
    delete node.children;
  }
  return {
    id: node.id,
    label: node.name,
    children: node.children
  }
}

//编辑变更企业
//变更企业
function changeDept(value) {
  if(value && value.id){
    form.value.sysId = value.id;
  }
  else{
  }
  console.log("变更了系统选择="+form.value.sysId+"@");
}
//数据导入

/** 导入按钮操作 */
function handleImport() {
  upload.title = "单据动作导入";
  upload.openup = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download('stability/action/importTemplate', {
  }, `单据动作导入模板_`+new Date().getTime()+`.xlsx`)
}

// 文件上传中处理
const handleFileUploadProgress = (event, file, fileList) =>{
  upload.isUploading = true;
}

// 文件上传成功处理
const handleFileSuccess = (response, file, fileList) =>{
  upload.openup = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg
      + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
  getList();
}

// 提交上传文件
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

function handleDownload(item)  {
  window.open(item, '_blank');
}

function getImagePreviewList(images)   {
  return images ? images.split(',').map(img => img) : []
}

/** 打开页面初始化**/
function initPage()
{
    console.log("初始化页面");
  //选择系统
  listAllCompany({areaId:null}).then(response => {
    companyOptions.value = proxy.handleTree(response.data, "id", "parentId");
    defaultCompany.value = companyOptions.value.length>0?companyOptions.value[0].id:null;
  });
  billDefineId.value = proxy.$route.query.billDefineId;
  const loginSrc = adminstyle().loginUrl.replace("/login", "").replace("/", "");
  curSys.value = getSysId(loginSrc);

    getList();
}

initPage();

</script>
